﻿using Com.JunCaiSoft.Permission.Entity;
using IdentityModel;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace Com.JunCaiSoft.Permission.Common
{
    /// <summary>
    /// 生成JWT字符串
    /// </summary>
    public class TokenExtension
    {
        // 密钥，注意不能太短
        public static string secretKey { get; set; } = "fishandnalar@msn.com";

        /// <summary>
        /// 获取AccessToken
        /// </summary>
        /// <returns></returns>
        public static string GetAccessToken(User user) 
        {
            //定义发行人issuer
            string iss = "JWTBearer.Auth";
            //定义受众人audience
            string aud = "api.auth";

            //定义许多种的声明Claim,信息存储部分,Claims的实体一般包含用户和一些元数据
            IEnumerable<Claim> claims = new Claim[]
            {
                    new Claim(JwtClaimTypes.Id,user.Id.ToString()),
                    new Claim(JwtClaimTypes.Name,user.UserName)
            };
            //notBefore  生效时间
            // long nbf =new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds();
            var nbf = DateTime.UtcNow;
            //expires   //过期时间
            // long Exp = new DateTimeOffset(DateTime.Now.AddSeconds(1000)).ToUnixTimeSeconds();
            var Exp = DateTime.UtcNow.AddSeconds(36000);
            //signingCredentials  签名凭证
            string SecurityKey = "fishandnalar@msn.com"; //SecurityKey 的长度必须 大于等于 16个字符
            var secret = Encoding.UTF8.GetBytes(SecurityKey);
            var key = new SymmetricSecurityKey(secret);
            var signcreds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            var jwt = new JwtSecurityToken(issuer: iss, audience: aud, claims: claims, notBefore: nbf, expires: Exp, signingCredentials: signcreds);
            var JwtHander = new JwtSecurityTokenHandler();
            var token = JwtHander.WriteToken(jwt);
            return token;
        }
    }
}
